/**
 * @description user 路由
 * @author 
 */
const router = require('koa-router')()
const { isExist,regitser,login,deleteCurUser,getCurUserInfo,changeUserinfo,changeUserPassword,logout } = require('../../control/user')
const { userValidate } = require('../../validator/user')
const { genValidator } = require('../../middleware/validator')
const { loginCheck } = require('../../middleware/loginCheck')

// 路由前缀
router.prefix('/api/user')

// 用户名是否存在
router.post('/isExist',async (ctx,next) => {
  let { userName } = ctx.request.body
  // console.log(userName)
  // 调用ctroll层isExist函数
  ctx.body = await isExist(userName)
})

// 用户注册
router.post('/register',genValidator(userValidate),async (ctx,next)=> {
  let userInfo = ctx.request.body
  // 调用ctroll层写入用户
  ctx.body = await regitser(userInfo)
})

// 登录
router.post('/login',async (ctx,next) => {
  let userInfo = ctx.request.body
  ctx.body = await login(ctx,userInfo)
})

// 获取用户信息
router.post('/getUserInfo',loginCheck,async (ctx,next)=> {
  ctx.body = await getCurUserInfo(ctx)
})

// 修改用户信息
router.patch('/changeUserInfo',loginCheck,genValidator(userValidate),async (ctx,next) => {
  let oldUserInfo = ctx.session.userInfo
  let newUserInfo = ctx.request.body
  ctx.body = await changeUserinfo(ctx,oldUserInfo,newUserInfo)
})

// 修改用户密码
router.patch('/changeUserPassword',loginCheck,genValidator(userValidate),async (ctx,next) => {
  let { password,newPassword } = ctx.request.body
  let { userName } = ctx.session.userInfo
  ctx.body = await changeUserPassword({ userName,password,newPassword })
})

// 退出登录
router.post('/logout',loginCheck,async (ctx,next) => {
  let result = await logout(ctx)
  ctx.body = result
})

// 删除用户,只能删除当前用户
router.post('/delete',loginCheck,async (ctx,next)=> {
  // 获取当前用户
  let { userName } = ctx.session.userInfo
  ctx.body = await deleteCurUser(userName)
})

module.exports = router
